package com.zhhl.controller;

import com.jld.base.common.bean.business.base.system.BSystemUserBean;
import com.jld.common.constants.ResCode;
import com.jld.common.log4j.JLDLogger;
import com.jld.common.util.MD5Util;
import com.jld.common.util.StringUtil;
import com.jld.common.vo.QueryDO;
import com.jld.common.vo.ResultDO;
import com.jld.common.vo.pageutil.PageUtil;
import java.beans.PropertyEditorSupport;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public abstract class BaseController {
	static Validator VAAIL = Validation.buildDefaultValidatorFactory().getValidator();

	protected final <T> ResultDO<T> checkParam(Object[] args) {
		if ((args == null) || (args.length == 0)) {
			return new ResultDO(true);
		}
		for (Object obj : args) {
			if (obj == null) {
				return new ResultDO(ResCode.COM_PARAMERROR.getResCode(),
						ResCode.COM_PARAMERROR.getResDescription());
			}
			Set vResult = VAAIL.validate(obj, new Class[0]);
			if (vResult.size() != 0) {
				Iterator localIterator = vResult.iterator();
				if (localIterator.hasNext()) {
					ConstraintViolation violation = (ConstraintViolation) localIterator
							.next();
					return new ResultDO(ResCode.COM_PARAMERROR.getResCode(),
							violation.getMessage());
				}
			}
		}
		return new ResultDO(true);
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils
						.escapeHtml4(text.trim()));
			}

			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
	}

	public static void main(String[] args) {
		System.out.println(MD5Util.md5(MD5Util.md5WithSalt(
				"15040910001000410000000143739313300010011000.001000.00",
				"admin")));
	}

	protected String getCurrentLoginName() {
		return getCurrentLoginUser().getLoginName();
	}

	protected BSystemUserBean getCurrentLoginUser() {
		Session session = SecurityUtils.getSubject().getSession();
		return (BSystemUserBean) session.getAttribute("currentUser");
	}

	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	protected HttpSession getSession(boolean isNew) {
		return getRequest().getSession(isNew);
	}

	protected QueryDO getPagerReqParam(Object bean, PageUtil<?> pager) {
		Map parms = new HashMap();
		parms.put("page", pager);
		parms.put("param", bean);
		return new QueryDO(parms);
	}

	protected Object getSessionAttribute(String name) {
		HttpSession session = getSession(false);
		return session != null ? session.getAttribute(name) : null;
	}

	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
	}

	protected String getParameter(String name) {
		try {
			return getRequest().getParameter(name) != null ? getRequest()
					.getParameter(name).toString().trim() : "";
		} catch (Exception e) {
			JLDLogger.error("参数：" + name + "接收失败！");
		}
		return "";
	}

	protected Map<String, String> getAllRequestParam(HttpServletRequest request) {
		Map res = new HashMap();
		Enumeration temp = request.getParameterNames();
		if (temp != null) {
			while (temp.hasMoreElements()) {
				String en = (String) temp.nextElement();
				String value = request.getParameter(en);
				res.put(en, value);

				if ((res.get(en) == null) || ("".equals(res.get(en)))) {
					res.remove(en);
				}
			}
		}
		return res;
	}

	protected ResultDO<String> toErrorResult(BindingResult br) {
		return new ResultDO(ResCode.COM_PARAMERROR.getResCode(),
				((ObjectError) br.getAllErrors().get(0)).getDefaultMessage()
						.toString());
	}

	protected ResultDO<String> toErrorResult(String code, String dedsc) {
		return new ResultDO(code, dedsc);
	}

	protected String toErrorResultString(BindingResult br) {
		ResultDO dojo = toErrorResult(br);
		return StringUtil.toJsonString(dojo);
	}

	protected String toErrorResultString(ResultDO<?> dojo) {
		return StringUtil.toJsonString(dojo);
	}

	protected String toErrorResultString(String code, String dedsc) {
		ResultDO dojo = toErrorResult(code, dedsc);
		return StringUtil.toJsonString(dojo);
	}

	protected ResultDO<String> toErrorResult(ResCode coded) {
		return new ResultDO(coded.getResCode(), coded.getResDescription());
	}

	protected <T> ResultDO<T> toSuccessResult(T br) {
		return new ResultDO(br);
	}

	protected <T> ResultDO<T> toSuccessResult() {
		return new ResultDO(true);
	}

	protected <T> ResultDO<T> toErrorResult(ResultDO<T> _sRd) {
		return new ResultDO(_sRd.getErrorCode(), _sRd.getErrorMsg(),
				_sRd.getObj());
	}

	protected String getBasePath(HttpServletRequest req) {
		StringBuffer baseUrl = new StringBuffer();
		String scheme = req.getScheme();
		int port = req.getServerPort();

		baseUrl.append(scheme);
		baseUrl.append("://");
		baseUrl.append(req.getServerName());
		if (((scheme.equals("http")) && (port != 80))
				|| ((scheme.equals("https")) && (port != 443))) {
			baseUrl.append(':');
			baseUrl.append(req.getServerPort());
		}
		return baseUrl.toString();
	}

	protected static String getIp(HttpServletRequest req) {
		String ip = req.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = req.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = req.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = req.getRemoteAddr();
		}
		ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
		return ip;
	}
}